<?php

namespace Modules\Common\General\Notification\Sms;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use Modules\Common\Dictionary\SmsType;
use Modules\Common\General\Notification\Sms\Exceptions\SmsBusinessException;
use Modules\Common\Models\Sms as SmsModel;
use Modules\Common\Models\SmsVerify;

class Sms
{
    protected $client;
    protected $signName;
    protected $accessKeyId;
    protected $accessKeySecret;
    //登录验证码模板
    protected $template_login_verify;
    protected $template_employee_withdraw;
    protected $template_enterprise_modify_password;
    //...

    protected $tag;

    public function __construct()
    {
        $this->signName = config('aliyun.sms.signName');
        $this->accessKeyId = config('aliyun.sms.accessKeyId');
        $this->accessKeySecret = config('aliyun.sms.accessKeySecret');
        $this->template_login_verify = config('aliyun.sms.templates.loginVerify');
        $this->template_employee_withdraw=config('aliyun.sms.templates.employeeWithdraw');
        $this->template_enterprise_modify_password=config('aliyun.sms.templates.enterpriseModifyPassword');
    }

    //发送登录验证码
    public function sendLoginVerify($mobile, $tag)
    {
        list($code, $json) = $this->randomCode();
        $this->tag = $tag;

        if(in_array($this->tag,['admin-login', 'h5-login','web-login'])){
            $this->send($mobile, $this->template_login_verify, $json, SmsType::VERIFY, $code);
        }

    }


    protected function randomCode()
    {
        return [$code = mt_rand(1000, 10000), json_encode(['code' => $code])];
    }

    protected function send($mobile, $TemplateCode, $TemplateParam, $type = SmsType::NOTIFY, $code = 0)
    {
        AlibabaCloud::accessKeyClient($this->accessKeyId, $this->accessKeySecret)
            ->regionId('cn-hangzhou')
            ->asDefaultClient();

        $result = null;
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'PhoneNumbers' => $mobile,
                        'SignName' => $this->signName,
                        'TemplateCode' => $TemplateCode,
                        'TemplateParam' => $TemplateParam,
                    ],
                ])
                ->request();
            $result = $result->toArray();

            if ($result['Code'] === 'OK') {
                $sms = SmsModel::createFromArray([
                    'mobile' => $mobile,
                    'sign_name' => $this->signName,
                    'template_code' => $TemplateCode,
                    'template_param' => $TemplateParam,
                    'status' => 1,
                ]);

                if ($type === SmsType::VERIFY) {
                    SmsVerify::createFromArray([
                        'tag' => $this->tag,
                        'sms_id' => $sms->id,
                        'mobile' => $mobile,
                        'code' => $code,
                        'status' => 1
                    ]);
                }
            } else {
                SmsBusinessException::new()
                    ->tellUser('短信发送失败！')
                    ->logAlert('阿里云短信业务逻辑错误！', ['result' => $result])
                    ->throw();
            }

        } catch (ClientException $e) {
            \Modules\Common\General\Notification\Sms\Exceptions\ClientException::new()
                ->tellUser('服务器繁忙！')
                ->logAlert('阿里云短信客户端错误！', ['error' => $e->getMessage()])
                ->throw();
        } catch (ServerException $e) {
            \Modules\Common\General\Notification\Sms\Exceptions\ServerException::new()
                ->tellUser('短信服务商繁忙！')
                ->logAlert('阿里云短信服务端错误！', ['error' => $e->getMessage()])
                ->throw();
        }
    }


}
